package com.tencreat.service.pt.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.constant.Constants;
import com.tencreat.common.core.domain.model.LoginUser;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.uuid.IdUtils;
import com.tencreat.domain.mall.MallGoods;
import com.tencreat.domain.pt.MallPt;
import com.tencreat.domain.pt.MallPtGoods;
import com.tencreat.domain.pt.vo.ResPtGoodsListPCVO;
import com.tencreat.domain.pt.dto.PtGoodAddDTO;
import com.tencreat.mapper.pt.MallPtGoodsMapper;
import com.tencreat.service.mall.IMallGoodsService;
import com.tencreat.service.pt.IMallPtGoodsService;
import com.tencreat.service.pt.IMallPtService;
import com.tencreat.service.pt.scheduler.CommonScheduler;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 拼团商品Service业务层处理
 *
 * @author tencreat
 * @date 2021-11-08
 */
@Service
@Slf4j
@Transactional
public class MallPtGoodsServiceImpl extends ServiceImpl<MallPtGoodsMapper, MallPtGoods> implements IMallPtGoodsService {
    //@Autowired
    IMallPtService mallPtService;

    @Autowired
    IMallGoodsService mallGoodsService;

    /**
     * 查询拼团商品
     *
     * @param id 拼团商品ID
     * @return 拼团商品
     */
    @Override
    public MallPtGoods selectMallPtGoodsById(ReqIdParam id) {
        return baseMapper.selectById(id.getId());
    }

    /**
     * 查询拼团商品列表
     *
     * @param mallPtGoods 拼团商品
     * @return 拼团商品
     */
    @Override
    public List<MallPtGoods> selectMallPtGoodsList(MallPtGoods mallPtGoods) {
        return baseMapper.selectList(Wrappers.query(mallPtGoods));
    }

    /**
     * 新增拼团商品
     *
     * @param mallPtGoods 拼团商品
     * @return 结果
     */
    @Override
    public int insertMallPtGoods(MallPtGoods mallPtGoods) {
        mallPtGoods.setCreateTime(LocalDateTime.now());
        return baseMapper.insert(mallPtGoods);
    }

    /**
     * 修改拼团商品
     *
     * @param mallPtGoods 拼团商品
     * @return 结果
     */
    @Override
    public int updateMallPtGoods(MallPtGoods mallPtGoods) {
        mallPtGoods.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(mallPtGoods);
    }

    /**
     * 批量删除拼团商品
     *
     * @param ids 需要删除的拼团商品ID
     * @return 结果
     */
    @Override
    public int deleteMallPtGoodsByIds(ReqIdsParam ids) {
        return baseMapper.deleteBatchIds(ids.getId());
    }

    /**
     * 删除拼团商品信息
     *
     * @param id 拼团商品ID
     * @return 结果
     */
    @Override
    public int deleteMallPtGoodsById(ReqIdParam id) {
        return baseMapper.deleteById(id.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int batchAdd(List<PtGoodAddDTO> vo, LoginUser loginCheck) throws SchedulerException {
        int sums = 0;

//        Date now = new Date();
        LocalDateTime now = LocalDateTime.now();

        vo.stream().forEach(item -> {
            int count = lambdaQuery().eq(MallPtGoods::getGoodsId, item.getGoodsId()).count();
            if (count > 0) {
                throw new CustomException("商品已存在");
            }
        });
        for (PtGoodAddDTO p : vo) {
            if (p.getEndGroupTime().compareTo(LocalDateTime.now()) < 0) {
                log.info("拼团截止时间不能小于当前时间!");
                throw new CustomException("拼团截止时间不能小于当前时间");
            }

            if (p.getDrawTime().isBefore(now)) {
                log.info("开奖时间不能小于当前时间!");
                throw new CustomException("开奖时间不能小于当前时间");
            }

            if (p.getDrawTime().isBefore(p.getEndGroupTime())) {
                log.info("开奖时间不能小于结束时间!");
                throw new CustomException("开奖时间不能小于结束时间");
            }

            MallGoods mallGoods = mallGoodsService.lambdaQuery().eq(MallGoods::getId, p.getGoodsId()).one();

            MallPtGoods mallPtGoods = new MallPtGoods();
            mallPtGoods.setGoodsId(p.getGoodsId());
            mallPtGoods.setPrice(mallGoods.getRetailPrice());
            mallPtGoods.setAwtoNum(1L);
            mallPtGoods.setGoodsJpg(mallGoods.getPicUrl());
            mallPtGoods.setRedeemablePoints(mallGoods.getRetailPrice().intValue());
            mallPtGoods.setZoneId(p.getZoneId());
            mallPtGoods.setSort(p.getSort());
            mallPtGoods.setDelFlag("0");
            mallPtGoods.setCreateBy(loginCheck.getUser().getUserId().toString());
            mallPtGoods.setCreateTime(LocalDateTime.now());
            sums += baseMapper.insert(mallPtGoods);


            String ptSn = IdUtils.generateGroupNumber();
            Optional<MallPt> lastPt = mallPtService.lambdaQuery().orderByDesc(MallPt::getSnIncrementing).last("limit 1").oneOpt();
            int inc = 0;
            if (lastPt.isPresent()) {
                int value = lastPt.map(MallPt::getSnIncrementing).orElse(225566);
//                int value= Integer.parseInt(lastPt.map(MallPt::getPtSn).orElse("").substring(10, 16));
                ptSn = ptSn + (value + 1);
                inc = value + 1;
            } else {
                ptSn = ptSn + "225566";
                inc = 225566;
            }
            MallPt mallPt = new MallPt();
            mallPt.setPtSn(ptSn);
            mallPt.setSnIncrementing(inc);
            mallPt.setPtGoodsId(mallPtGoods.getId());
            mallPt.setPtNumberP(0L);
            mallPt.setIsLate(true);
            mallPt.setActualJoinNumber(0L);
            mallPt.setStartGroupTime(p.getStartGroupTime());
            mallPt.setEndGroupTime(p.getEndGroupTime());
            mallPt.setDrawTime(p.getDrawTime());
            mallPt.setLotteryStatus(2);
            mallPt.setNumberOfPeriods(1);
            mallPt.setStartedNext("0");
            mallPt.setDelFlag("0");
            mallPt.setCreateBy(loginCheck.getUser().getUserId().toString());
            mallPt.setCreateTime(LocalDateTime.now());

            mallPtService.save(mallPt);


            /* =======开奖定时触发器=======*/
            //CommonScheduler.ptJob(Date.from(p.getDrawTime().atZone(ZoneId.systemDefault()).toInstant()), mallPt.getId().toString(), Constants.GROUP_NAME_PT);
        }

        return sums;
    }

    @Override
    public Page<ResPtGoodsListPCVO> list(Page<ResPtGoodsListPCVO> page,
                                         String ptSn, Long goodsId, Integer zoneId, Integer
                                                 lotteryStatus, Integer goodsType, Integer goodsStarts) {
//        Date now = new Date();
        LocalDateTime now = LocalDateTime.now();
        Page<ResPtGoodsListPCVO> list = baseMapper.list(page, ptSn, goodsId, zoneId, lotteryStatus, goodsType, goodsStarts);
        List<ResPtGoodsListPCVO> records = list.getRecords();
        records.forEach(i -> {
            if (now.isAfter(i.getEndGroupTime()) && now.isBefore(i.getDrawTime()) && i.getLotteryStatus() != 1) {
                i.setLotteryStatus(1);
            }
            if (now.isAfter(i.getDrawTime()) && i.getLotteryStatus() != 3) {
                i.setLotteryStatus(3);
            }

        });

        return list;
    }
}
